package com.ming.transaction.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ming.transaction.common.Result;
import com.ming.transaction.config.RabbitMQConfig;
import com.ming.transaction.entity.Goods;
import com.ming.transaction.entity.Order;
import com.ming.transaction.mapper.OrderMapper;
import com.ming.transaction.service.IGoodsService;
import com.ming.transaction.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 陈仕健
 * @since 2023-05-14
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Resource
    private IGoodsService goodsService;


    /**
     * 交易接口
     * @param order
     * @return
     */
    @Override
    public Result addOrder(Order order) {
        // order 获取了 卖家，买家，商品ID，交易数量，交易价格
        // 1.随机生成订单编号
        order.setOrderId(RandomUtil.randomString(25));
        // 2.获取商品信息并减少数量
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",order.getGoodsId());
        queryWrapper.eq("unumber",order.getSallNumber());
        Goods one = goodsService.getOne(queryWrapper);
        if(one == null){
            return Result.fail("未知错误，请服务失败！");
        }
        // 如果销售完了之后数量不足，则商品状态设为 0 并保存数据
        int num = one.getGnum()-order.getOrderNumber();
        if(num == 0){
            one.setStatus(2);
            one.setGnum(num);
        }
        if(num < 0){
            return  Result.fail("购买错误超过销售数量！");
        }
        one.setGnum(num);
        goodsService.saveOrUpdate(one);
        // 保存订单
        save(order);
        return Result.success("商品购买成功！");
    }
}
